﻿using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseTransfer.Logs
{
    public class LogFactory
    {
        private static ILog logger = LogFactory.GetLogger(typeof(LogFactory));

        internal static ILog GetLogger(Type type)
        {
            return LogManager.GetLogger(type); ;
        }

        /// <summary>
        /// Initializes all the loggers in the program
        /// and sets the log level to error
        /// This routine goes through the DatabaseTransfer namespace and finds
        /// all the classes that have a logger defined
        /// </summary>
        public static void SetupLoggers()
        {
            string @namespace = "DatabaseTransfer";

            foreach(Type classType in AppDomain.CurrentDomain.GetAssemblies().
                SelectMany(t => t.GetTypes()).
                Where(t => t.IsClass && t.Namespace != null && t.Namespace.StartsWith(@namespace)))
            {
                foreach (FieldInfo field in classType.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
                {
                    if (field.FieldType == typeof(ILog))
                    {
                        LogManager.GetLogger(classType);
                        break;
                    }
                }
            }

            //This has to be at the end of the list to make sure they are all 
            //Set to be error level
            foreach (ILog log in LogManager.GetCurrentLoggers())
            {
                ((log4net.Repository.Hierarchy.Logger)log.Logger).Level = log4net.Core.Level.Error;
            }
        }
    }
}
